<?php

declare(strict_types=1);

namespace App\Request;


use App\Exception\MessageException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class BaseCommonRequest
{

    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    /**
     * 验证器名称
     * @var string
     */
    protected $name = '';

    /**
     * 验证规则
     * @var array
     */
    protected $rules = [];

    /**
     * 验证提示
     * @var array
     */
    protected $messages = [];

    /**
     * 验证字段自定义
     * @var array
     */
    protected $attributes = [];


    public function __construct()
    {
        $this->rules = $this->rules();
        if (empty($this->rules)) {
            throw new MessageException('验证规则不能为空');
        }
        if (!is_array($this->rules)) {
            throw new MessageException('验证规则必须为数组');
        }
        // if (empty($this->messages)) {
        //     throw new MessageException('验证提示不能为空');
        // }
        // if (!is_array($this->messages)) {
        //     throw new MessageException('验证提示必须为数组');
        // }

    }


    /**
     * Note - 执行验证规则
     * DateTime 2024/8/16 10:32
     * User Admin
     * @param array $params
     * @param string $scene
     * @return void
     */
    public function execute(array $params, $scene = '')
    {
        if (empty($params)) {
            throw new MessageException('缺少必要参数');
        }
        $rules = $this->rules;
        if (isset($this->rules[$scene])) {
            $rules = $this->rules[$scene];
        }
        $validator = $this->validationFactory->make($params, $rules, $this->messages);
        $validator->validate();
        // if ($validator->fails()){
        //     throw new \Exception($validator->errors()->first());
        // }
    }
}
